<template>
  <div id="dictChildManage">
    <Splitpanes>
      <!-- 设计模式  -->
      <Pane size="35" v-if="isDictShow">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">设计模式</div>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="findDictList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addDictForm"></vxe-button>
          </template>
        </vxe-toolbar>

        <div class="designTable">
          <vxe-table ref="dictTable" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="dictList" :loading="tloading" @current-change="dictRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
            <vxe-column field="code" title="字段编码" width="110"></vxe-column>
            <vxe-column field="name" title="字段名称" width="110"></vxe-column>
            <vxe-column field="sx" title="顺序" width="50"></vxe-column>
            <vxe-column title="操作" fixed="right">
              <template #default="{ row }">
                <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle v-if="row.isParentEdit == '0'" @click.native="deleteDict(row)"></vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>

      <!-- 设计模式右侧表单 -->
      <Pane size="65" v-if="isDictShow">
        <div class="toolbartitle">组件属性</div>
        <el-form ref="dictFormRef" :model="dictForm" :rules="dictFormRule" class="form-input-m" label-width="90px" inline-message v-loading="tloading">
          <el-row>
            <el-col :span="24">
              <el-form-item label="字段类型" prop="fieldType">
                <el-select placeholder="请选择字段类型" :teleported="false" v-model="dictForm.fieldType" style="width: 200px" clearable>
                  <el-option v-for="dict in fieldTypeList" :key="dict.code" :label="dict.name" :value="dict.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item prop="code" label="字段名">
                <el-input type="text" v-model="dictForm.code" placeholder="请输入字段名" clearable></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item prop="name" label="标题">
                <el-input type="text" v-model="dictForm.name" placeholder="请输入标题" clearable></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item prop="classify" label="组件类型">
                <el-radio-group v-model="dictForm.classify">
                  <el-radio-button label="1" @click.prevent="changeCorrection('1')">是否标识</el-radio-button>
                  <el-radio-button label="2" @click.prevent="changeCorrection('2')">表达式输入</el-radio-button>
                  <el-radio-button label="3" @click.prevent="changeCorrection('3')">字典输入</el-radio-button>
                  <el-radio-button label="4" @click.prevent="changeCorrection('4')">表输入</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="dictForm.classify == '1'">
              <el-form-item prop="type" label="前缀类型">
                <el-select v-model="dictForm.prefixType" filterable placeholder="请选择规则类型">
                  <el-option v-for="typeObj in ruleTypeList" :key="typeObj.code" :label="typeObj.name" :value="typeObj.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="dictForm.classify == '1'">
              <el-form-item prop="prefixRule" label="前缀规则">
                <el-input type="text" v-model="dictForm.prefix"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="dictForm.classify == '1'">
              <el-form-item prop="infixType" label="中缀类型">
                <el-select v-model="dictForm.infixType" filterable placeholder="请选择规则类型">
                  <el-option v-for="typeObj in ruleTypeList" :key="typeObj.code" :label="typeObj.name" :value="typeObj.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="dictForm.classify == '1'">
              <el-form-item prop="infixRule" label="中缀规则">
                <el-input type="text" v-model="dictForm.infix"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="dictForm.classify == '1'">
              <el-form-item prop="suffixType" label="后缀类型">
                <el-select v-model="dictForm.suffixType" filterable placeholder="请选择规则类型">
                  <el-option v-for="typeObj in sufTypeList" :key="typeObj.code" :label="typeObj.name" :value="typeObj.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="dictForm.classify == '1'">
              <el-form-item prop="suffixRule" label="后缀规则">
                <el-input type="text" v-model="dictForm.suffix"></el-input>
              </el-form-item>
            </el-col>

            <!-- <el-col :span="24" v-if="dictForm.classify == '1'">
              <el-form-item prop="aotuNum" label="自增量">
                <el-input-number v-model="dictForm.aotuNum" :min="1" :max="1000" />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="dictForm.classify == '1'">
              <el-form-item prop="prefix" label="前缀">
                <el-input
                  type="text"
                  v-model="dictForm.prefix"
                  placeholder="请输入前缀"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="dictForm.classify == '1'">
              <el-form-item prop="suffix" label="后缀">
                <el-input
                  type="text"
                  v-model="dictForm.suffix"
                  placeholder="请输入后缀"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="24" v-if="dictForm.classify == '2'">
              <el-form-item label="选择表达式" prop="expression">
                <el-select placeholder="请选择表达式" :teleported="false" v-model="dictForm.expression">
                  <el-option v-for="dict in cyhsDictList" :key="dict.id" :label="dict.name" :value="dict.expression"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="选择字段" prop="correField" v-if="dictForm.classify == '2'">
                <el-select placeholder="请选择字段" :teleported="false" v-model="dictForm.correField">
                  <el-option v-for="dict in dictList" :key="dict.id" :label="dict.name" :value="dict.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24" v-if="dictForm.classify == '3'">
              <el-form-item label="选择字典" prop="dict">
                <el-select placeholder="请选择字典" :teleported="false" v-model="dictForm.dict">
                  <el-option v-for="dict in dictAllList" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24" v-if="dictForm.classify == '4'">
              <el-form-item label="选择表" prop="correTable">
                <vxe-pulldown ref="pulldownRef" transfer>
                  <template #default>
                    <vxe-input v-model="dictForm.correTable" suffix-icon="vxe-icon-table" placeholder="实现下拉分页表格" @keyup="keyupEvent" @focus="focusEvent" @suffix-click="suffixClick"></vxe-input>
                  </template>
                  <template #dropdown>
                    <div class="my-dropdown4">
                      <vxe-grid border auto-resize height="auto" :row-config="{ isHover: true }" :loading="loading" :pager-config="pagerConfig" :data="tableData" :columns="tableColumn" @cell-click="cellClickEvent">
                      </vxe-grid>
                    </div>
                  </template>
                </vxe-pulldown>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="dictForm.classify == '4'">
              <el-form-item label="选择字段" prop="correColumn">
                <el-select placeholder="请选择字段" :teleported="false" v-model="dictForm.correColumn">
                  <el-option v-for="dict in correColumnList" :key="dict.columnId" :label="dict.comments" :value="dict.columnName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="dictForm.classify == '4'">
              <el-form-item label="选择字段2" prop="correColumn2">
                <el-select placeholder="请选择字段2" :teleported="false" v-model="dictForm.correColumn2">
                  <el-option v-for="dict in correColumnList" :key="dict.columnId" :label="dict.comments" :value="dict.columnName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="选择字段" prop="correField" v-if="dictForm.classify == '4'">
                <el-select placeholder="请选择字段" :teleported="false" v-model="dictForm.correField">
                  <el-option v-for="dict in dictList" :key="dict.id" :label="dict.name" :value="dict.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item prop="order" label="排序">
                <el-input-number v-model="dictForm.sx" :min="1" :max="1000" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item class="form-footer">
                <template #default>
                  <el-button type="primary" :disabled="dictForm.isParentEdit == '1'" @click="saveDict('dictFormRef')">保存</el-button>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </Pane>

      <!-- 预览模式  -->
      <Pane size="65" v-if="isDetailShow">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">预览模式</div>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="lookLoading" @click="findDictDetailList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建字典值" @click="addDetail()"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="导出" @click="export1"></vxe-button>
            <el-upload class="upload-demo" :headers="headers" :data="paramData" :action="uploadFilePath" :show-file-list="false" multiple :on-success="onSuccess" :on-error="onError">
              <vxe-button type="text" content="导入" class-name="padding-lr-xs" class="button-blue padding-lr-xs" @click="upload()" />
            </el-upload>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveDetailList"></vxe-button>
          </template>
        </vxe-toolbar>

        <div class="previewTable">
          <vxe-table ref="detailTable" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="detailList" :loading="lookLoading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :keyboard-config="{
              isArrow: true,
              isTab: true,
              isEdit: true
            }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
            <vxe-column v-for="(item, index) in dictList" :key="index" :field="item.code" :title="item.name" width="130" :edit-render="{}">
              <template #default="{ row, rowIndex, column }">
                <span v-if="item.code == 'isEdit'">{{ row[item.code] === '1' ? '否' : '是' }}</span>
                <div v-else-if="item.fieldType == 'color'">
                  <span class="margin-left-xs padding-lr-xs" :style="{ background: `${row[item.code]}` }">{{ row[item.code] }}</span>
                </div>
                <span v-else>{{ row[item.code] }}</span>
              </template>

              <template #edit="{ row, rowIndex, column }">
                <!-- 是否删改 开关 -->
                <vxe-switch v-model="row[item.code]" v-if="item.code == 'isEdit'" open-label="是" close-label="否" open-value="0" close-value="1"></vxe-switch>

                <!-- 选择字典  -->
                <vxe-select v-model="row[item.code]" placeholder="可清除" clearable v-else-if="item.classify == '3'" @focus="getSecletDictDetailById(item)">
                  <vxe-option v-for="(selectDetail, index) in selectDetailList" :key="index" :value="selectDetail.code" :label="selectDetail.name"></vxe-option>
                </vxe-select>

                <!-- 选择动态表  -->
                <vxe-select v-model="row[item.code]" placeholder="可清除" clearable v-else-if="item.classify == '4'" @focus="getTableDataList(item)" @change="selectTableData($event, item, row)">
                  <vxe-option v-for="(tableData, index) in tableDataList" :key="index" :value="tableData[item.correColumn]" :label="tableData[item.correColumn2]"></vxe-option>
                </vxe-select>

                <!-- 自动生成 -->
                <vxe-input v-else-if="
                    dictList.find((it) => it.classify == '2') &&
                    dictList.find((it) => it.classify == '2').correField == item.code
                  " @change="getBdsResult(item.code, row[item.code], row)" v-model="row[item.code]" type="text"></vxe-input>

                <!-- 禁用 -->
                <vxe-input v-else-if="item.classify == '1'" v-model="row[item.code]" disabled type="text"></vxe-input>
                <!-- 组件类型什么也没选 -->
                <vxe-input v-else v-model="row[item.code]" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="sx" title="排序" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.sx" type="text"></vxe-input>
              </template>
            </vxe-column>

            <vxe-column title="操作" align="center" fixed="right">
              <template #default="{ row }">
                <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle v-if="panduanIsEdit(row)" @click.native="deleteDetail(row)"></vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>
    </Splitpanes>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import { AppStore } from '../../stores/store';
import { isEmpty } from 'lodash';
import { notifyMessage, notifyType } from '@/utils/common';

//暴露属性和方法
defineExpose({
  initPage,
  showDictData, //切换设计模式
  showDetailData //切换预览模式
});

// 全局变量定义区 ==========
let store = AppStore();
let isDictShow = ref(true); //默认显示设计模式
let isDetailShow = ref(false); //预览模式
// 加载状态
let tloading = ref(false); //设计模式表格
let lookLoading = ref(false); //预览模式表格

let dictList: any = reactive([]); //设计模式表格数据
let detailList: any = reactive([]); //预览模式表格数据

// 设计模式表单
let dictForm = reactive({
  id: null,
  pid: '',
  orgId: '',
  code: '',
  name: '',
  grade: 1,
  sx: 1,
  value: '',
  bz: '',
  classify: '',
  aotuNum: 1,
  prefixType: '',
  prefix: '',
  infixType: '',
  infix: '',
  suffixType: '',
  suffix: '',
  expression: '',
  isParentEdit: '',
  dict: '',
  fieldType: '',
  correField: '',
  correTable: '',
  correColumn: '',
  correColumn2: ''
});

// 设计模式表单校验
let dictFormRule = {
  name: [
    {
      required: true,
      message: '请输入标题',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

// 设计模式表单 字段类型选择
let fieldTypeList: any = [
  { code: 'input', name: '输入框' },
  { code: 'select', name: '下拉框' },
  { code: 'radio', name: '单选框' },
  { code: 'checkbox', name: '复选框' },
  { code: 'color', name: '颜色' }
];

// 设计模式表单:1：前缀 中缀类型
let ruleTypeList: any = [
  { code: 'gdz', name: '固定值' },
  { code: 'rqz', name: '日期值' }
];
// 设计模式表单 1：后缀类型
let sufTypeList: any = [{ code: 'seq', name: '自增序列' }];

//动态表输入的表属性
let tableColumn: any = reactive([
  { field: 'TABLE_NAME', title: '表名' },
  { field: 'COMMENTS', title: '表说明' }
]);
let tableData: any = reactive([]);
let tableList: any = reactive([]);
let correColumnList: any = reactive([]);

//设计模式表单 2：选择表达式(首字母函数 全拼函数)
let cyhsDictList: any = reactive([]);

//设计模式表单 3：选择:字典
let dictAllList: any = reactive([]);

let detailTable = ref(); //预览模式table表格Ref

let sltDict: any = {}; //接收字段传来的row数据

let selectDetailList: any = reactive([]); //选择字典

let tableDataList: any = reactive([]); //选择动态表集合
let headers = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
};
// 请求参数数据
const paramData: any = reactive({
  dictId: '',
  grade: ''
});
// 上传图片
const uploadFilePath = ref((window as any).apiUrl.VITE_SERVER_URL + '/api/sys/basDictDetail/uploadDetailByExcel');
// 方法定义区 =============
function initPage(row: any) {
  detailList.length = 0;
  sltDict = row;
  findDictList(); //获取设计模式table数据
  getCyhsDictList(); //获取设计模式表单的选择表达式
  findAllDictList(); //获取设计模式表单的选择字典
  findAllTableList();
}

// 设计模式/预览模式切换 切换设计模式
function showDictData() {
  isDictShow.value = true;
  isDetailShow.value = false;
  proxy.$nextTick(() => {
    if (IsEmpty(dictList.find((item) => item.id == dictForm.id))) {
      dictRowClick({ row: dictList[0] }); //默认选中第一条数据
    } else {
      dictRowClick({ row: dictList.find((item) => item.id == dictForm.id) }); //默认选中第一条数据
    }
  });
}

// 设计模式/预览模式切换 切换预览模式
function showDetailData() {
  isDictShow.value = false;
  isDetailShow.value = true;
}

// 获取设计模式table数据
function findDictList() {
  dictList.length = 0; //放入数据前清空数据
  clearForm();
  if (IsEmpty(sltDict)) {
    // VxeMessage('请选择字典', VxeNotifyType.error);
    return;
  }
  tloading.value = true;
  const url = '/api/sys/basDict/findDictList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { pid: sltDict.id, grade: 1 } })
    .then((res: any) => {
      dictList.push(...res.data);
      findDictDetailList();
      dictRowClick({ row: dictList[0] }); //默认选中第一条数据
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
    });
}

// 点击设计模式表格当前行触发右侧表单变化
function dictRowClick({ row }: any) {
  if (IsEmpty(row)) {
    clearForm();
  } else {
    (proxy.$refs.dictTable as any).setCurrentRow(row);
    setDictForm(row);
  }
}

// 清空设计模式表单
function clearForm() {
  dictForm.id = null;
  dictForm.pid = '';
  dictForm.orgId = '';
  dictForm.code = '';
  dictForm.name = '';
  dictForm.grade = 1;
  dictForm.sx = 1;
  dictForm.value = '';
  dictForm.bz = '';
  dictForm.classify = '';
  dictForm.aotuNum = 1;
  dictForm.isParentEdit = '';
  dictForm.prefixType = '';
  dictForm.prefix = '';
  dictForm.infixType = '';
  dictForm.infix = '';
  dictForm.suffixType = '';
  dictForm.suffix = '';
  dictForm.expression = '';
  dictForm.dict = '';
  dictForm.fieldType = '';
  dictForm.correField = '';
  dictForm.correTable = '';
  dictForm.correColumn = '';
  dictForm.correColumn2 = '';
}

// 设计模式表单变化
function setDictForm(row: any) {
  dictForm.code = row.code;
  dictForm.id = row.id;
  dictForm.grade = row.grade;
  dictForm.isParentEdit = row.isParentEdit;
  dictForm.name = row.name;
  dictForm.pid = row.pid;
  dictForm.sx = row.sx;
  dictForm.orgId = row.orgId;
  dictForm.value = row.value;
  dictForm.bz = row.bz;
  dictForm.classify = row.classify;
  dictForm.aotuNum = row.aotuNum;
  dictForm.prefixType = row.prefixType;
  dictForm.prefix = row.prefix;
  dictForm.infixType = row.infixType;
  dictForm.infix = row.infix;
  dictForm.suffixType = row.suffixType;
  dictForm.suffix = row.suffix;
  dictForm.expression = row.expression;
  dictForm.dict = row.dict;
  dictForm.fieldType = row.fieldType;
  dictForm.correField = row.correField;
  dictForm.correTable = row.correTable;
  dictForm.correColumn = row.correColumn;
  dictForm.correColumn2 = row.correColumn2;
  if (dictForm.classify == '4' && dictForm.correTable != '') {
    getTableColumns();
  }
}

// 删除选中字段的属性
function deleteDict(row: any) {
  proxy
    .$confirm('确定删除此属性？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/sys/basDict/deleteDict';
      proxy.$http.post(url, row).then((res: any) => {
        if (res.status.code === 1) {
          findDictList();
          VxeMessage('删除属性成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

// 新建设计模式右侧表单
function addDictForm() {
  clearForm();
  if (dictList.findIndex((item) => item.code == 'isEdit') > -1) {
    dictForm.sx = dictList.length;
  } else {
    dictForm.sx = dictList.length + 1;
  }

  (proxy.$refs.dictTable as any).clearCurrentRow();
}

// 改变设计模式的组件类型 3选1
function changeCorrection(item: any) {
  // item == dictForm.classify ? (dictForm.classify = '') : (dictForm.classify = item);
  // console.log(dictForm);
  if (item == dictForm.classify) {
    dictForm.classify = '';
  } else {
    dictForm.classify = item;
  }
}

// 获取设计模式表单的选择表达式
function getCyhsDictList() {
  cyhsDictList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { code: 'zdcyhs' } })
    .then((res: any) => {
      cyhsDictList.push(...res.data);
    })
    .catch((err: any) => {});
}

// 获取设计模式 选择字典
function findAllDictList() {
  dictAllList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDict/findDictList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { grade: 0 } })
    .then((res: any) => {
      dictAllList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取获取设计模式选择字典失败',VxeNotifyType.error)
    });
}

// 设计模式 右侧表单保存
function saveDict(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }

    if (dictForm.id === null) {
      const url = '/api/sys/basDict/addDict';
      const user = {
        pid: sltDict.id,
        code: dictForm.code,
        name: dictForm.name,
        grade: 1,
        sx: dictForm.sx,
        bz: dictForm.bz,
        classify: dictForm.classify,
        aotuNum: dictForm.aotuNum,
        prefixType: dictForm.prefixType,
        prefix: dictForm.prefix,
        infixType: dictForm.infixType,
        infix: dictForm.infix,
        suffixType: dictForm.suffixType,
        suffix: dictForm.suffix,
        expression: dictForm.expression,
        dict: dictForm.dict,
        fieldType: dictForm.fieldType,
        correField: dictForm.correField,
        correTable: dictForm.correTable,
        correColumn: dictForm.correColumn,
        correColumn2: dictForm.correColumn2,
        orgId: !isEmpty(dictForm.orgId) ? dictForm.orgId : store.userInfo.orgId
      };
      proxy.$http
        .post(url, user)
        .then((res: any) => {
          VxeMessage('新增属性成功', VxeNotifyType.success);
          clearForm();
          findDictList();
        })
        .catch((err: any) => {
          VxeMessage('新增属性失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/api/sys/basDict/editDict';
      const user = {
        id: dictForm.id,
        code: dictForm.code,
        name: dictForm.name,
        sx: dictForm.sx,
        bz: dictForm.bz,
        classify: dictForm.classify,
        aotuNum: dictForm.aotuNum,
        prefixType: dictForm.prefixType,
        prefix: dictForm.prefix,
        infixType: dictForm.infixType,
        infix: dictForm.infix,
        suffixType: dictForm.suffixType,
        suffix: dictForm.suffix,
        expression: dictForm.expression,
        dict: dictForm.dict,
        fieldType: dictForm.fieldType,
        correField: dictForm.correField,
        correTable: dictForm.correTable,
        correColumn: dictForm.correColumn,
        correColumn2: dictForm.correColumn2
      };
      proxy.$http
        .post(url, user)
        .then((res: any) => {
          VxeMessage('修改属性成功', VxeNotifyType.success);
          setTimeout(() => {
            clearForm();
            findDictList();
          }, 500);
        })
        .catch((err: any) => {
          VxeMessage('修改属性失败', VxeNotifyType.success);
        });
    }
  });
}

// 获取预览模式表格数据
function findDictDetailList() {
  lookLoading.value = true;
  detailList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { pid: sltDict.id } })
    .then((res: any) => {
      detailList.push(...res.data);
      lookLoading.value = false;
    })
    .catch((err: any) => {
      lookLoading.value = false;
      VxeMessage('获取预览模式列表异常', VxeNotifyType.error);
    });
}

// 预览模式——新建字典值
function addDetail() {
  if (dictList.length > 0) {
    const row: any = {};
    for (const item of dictList) {
      row[item.code] = '';
    }
    row.isEdit = '0';
    row.isParentEdit = sltDict.isEdit;
    row.sx = detailList.length == 0 ? 1 : Number(detailList[detailList.length - 1].sx) + 1;
    detailList.push(row);
  } else {
    VXETable.modal.message({ content: '请选择基础字典', status: 'error' });
  }
}
async function export1() {
  const blob = new Blob([], { type: 'application/excel;charset=utf-8' });
  const downloadElement = document.createElement('a');
  const href = window.URL.createObjectURL(blob); //创建下载链接
  const fileUrl = (window as any).apiUrl.VITE_SERVER_URL + '/api/sys/basDictDetail/export';

  downloadElement.href = fileUrl + '?pid=' + sltDict.id; // 此处可以通过拼接字符串的方式传递参数
  document.body.appendChild(downloadElement);
  downloadElement.click(); // 点击下载
  document.body.removeChild(downloadElement); // 下载完成之后移除元素
  window.URL.revokeObjectURL(href); // 释放掉blob对象
}

// 预览模式最上层工具栏的保存按钮
async function saveDetailList() {
  // 获取表格实例
  let $Xtable = proxy.$refs.detailTable;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.commonId && p.commonId !== '';
    });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = detailList.filter((e: any) => {
      return !e.commonId || e.commonId === '';
    });

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    const saveOrUpdateitems = [] as any[];
    updateRecords.forEach((e: any) => {
      let moduleAddParam = e;
      for (const item of dictList) {
        const itemtemp = JSON.parse(JSON.stringify(item));
        itemtemp.value = moduleAddParam[item.code];
        itemtemp.sx = moduleAddParam.sx;
        itemtemp.id = '';
        itemtemp.pid = item.id;
        itemtemp.grade = moduleAddParam.grade;
        itemtemp.commonId = moduleAddParam.commonId;
        saveOrUpdateitems.push(itemtemp);
      }
    });

    // 新增
    InsertRecords.forEach((e: any) => {
      const moduleAddParam = e;
      for (const item of dictList) {
        const itemtemp = JSON.parse(JSON.stringify(item));
        itemtemp.value = moduleAddParam[item.code];
        itemtemp.sx = moduleAddParam.sx;
        itemtemp.id = '';
        itemtemp.pid = item.id;
        itemtemp.grade = 2;
        itemtemp.orgId = store.userInfo.orgId;
        saveOrUpdateitems.push(itemtemp);
      }
    });

    //批量一起新增
    const obj = {
      detailList: saveOrUpdateitems
    };
    if (obj.detailList.length > 0) {
      proxy.$http
        .post('/api/sys/basDictDetail/saveOrUpdateDetail', obj)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            // setTimeout(() => {
            findDictDetailList();
            // }, 500);
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('更新字典值异常', VxeNotifyType.error);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }
}
// 预览模式最上层工具栏的保存按钮
async function saveDetailList2() {
  // 获取表格实例
  let $Xtable = proxy.$refs.detailTable;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.commonId && p.commonId !== '';
    });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = detailList.filter((e: any) => {
      return !e.commonId || e.commonId === '';
    });

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    const updateitems = [] as any[];
    updateRecords.forEach((e: any) => {
      let moduleAddParam = e;
      for (const item of dictList) {
        const itemtemp = JSON.parse(JSON.stringify(item));
        itemtemp.value = moduleAddParam[item.code];
        itemtemp.sx = moduleAddParam.sx;
        itemtemp.id = '';
        itemtemp.pid = item.id;
        itemtemp.grade = moduleAddParam.grade;
        itemtemp.commonId = moduleAddParam.commonId;
        updateitems.push(itemtemp);
      }
    });

    const updateobj = {
      detailList: updateitems
    };
    if (updateobj.detailList.length > 0) {
      //批量修改
      proxy.$http
        .post('/api/sys/basDictDetail/editBatchDetail', updateobj)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改字典值成功', VxeNotifyType.success);
          } else {
            VxeMessage('修改字典值失败', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('修改字典值异常', VxeNotifyType.error);
        });
    }

    // 新增
    const items = [] as any[];
    InsertRecords.forEach((e: any) => {
      const moduleAddParam = e;
      for (const item of dictList) {
        const itemtemp = JSON.parse(JSON.stringify(item));
        itemtemp.value = moduleAddParam[item.code];
        itemtemp.sx = moduleAddParam.sx;
        itemtemp.id = '';
        itemtemp.pid = item.id;
        itemtemp.grade = 2;
        items.push(itemtemp);
      }
    });

    //批量一起新增
    const obj = {
      detailList: items
    };
    if (obj.detailList.length > 0) {
      proxy.$http
        .post('/api/sys/basDictDetail/addBatchDetail', obj)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('新增字典值成功', VxeNotifyType.success);
          } else {
            VxeMessage('新增字典值失败', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('新增字典值异常', VxeNotifyType.error);
        });
    }

    setTimeout(() => {
      findDictDetailList();
    }, 500);
  } else {
    return;
  }
}

// 重复？ 预览模式最上层工具栏的保存按钮
async function saveDetailList1() {
  const $table = proxy.$refs.detailTable;
  if ($table) {
    const updateRecords = await $table.getUpdateRecords().filter((p: any) => {
      return p.commonId && p.commonId !== '';
    });

    const InsertRecords = await $table.getInsertRecords().filter((m: any) => {
      return !m.commonId || m.commonId === '';
    });

    // 修改字典值
    updateRecords.forEach((e: any) => {
      let moduleAddParam = e;
      const items = [] as any[];
      for (const item of dictList) {
        const itemtemp = JSON.parse(JSON.stringify(item));
        itemtemp.value = moduleAddParam[item.code];
        itemtemp.sx = moduleAddParam.sx;
        itemtemp.id = '';
        itemtemp.pid = item.id;
        itemtemp.grade = moduleAddParam.grade;
        itemtemp.commonId = moduleAddParam.commonId;
        items.push(itemtemp);
      }
      const obj = {
        detailList: items
      };
      const url = '/api/sys/basDictDetail/editBatchDetail';
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改字典值成功', VxeNotifyType.success);
          }
        })
        .catch((err: any) => {
          VxeMessage('修改字典值异常', VxeNotifyType.error);
        });
    });

    // 新增机构
    InsertRecords.forEach((ele: any) => {
      const moduleAddParam = e;
      const items = [] as any[];
      for (const item of dictList) {
        const itemtemp = JSON.parse(JSON.stringify(item));
        itemtemp.value = moduleAddParam[item.code];
        itemtemp.sx = moduleAddParam.sx;
        itemtemp.id = '';
        itemtemp.pid = item.id;
        itemtemp.grade = 2;
        items.push(itemtemp);
      }
      const obj = {
        detailList: items
      };

      const url = '/api/sys/basDictDetail/addBatchDetail';
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('新增字典值成功', VxeNotifyType.success);
          }
        })
        .catch((err: any) => {
          VxeMessage('新增字典值异常', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      findDictDetailList();
    }, 500);
  } else {
    return;
  }
}

// 删除预览模式某一行的字典值
function deleteDetail(row: any) {
  proxy
    .$confirm('确定删除此字典值数据？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/sys/basDictDetail/deleteBatchDetail';
      if (row.commonId) {
        proxy.$http.post(url, row).then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('删除字典值成功', VxeNotifyType.success);
          } else {
            VxeMessage('删除字典值失败', VxeNotifyType.error);
          }
          findDictDetailList(); //重新获取预览模式表格数据
        });
      } else {
        // 删除的新增的空白数据 不走接口
        const $table = detailTable.value;
        if ($table) {
          await $table.remove(row);
          detailList.splice(row.sx - 1);
          VxeMessage('删除成功', VxeNotifyType.success);
        }
      }
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

// ------------------------------------------------------------
//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}

function panduanIsEdit(row: any) {
  if (row.commonId == undefined) {
    return true;
  } else {
    if (row.isEdit == undefined) {
      return row.isParentEdit == '0';
    } else {
      if (!(row.isParentEdit == '0')) {
        return false;
      } else {
        return row.isEdit == '0';
      }
    }
  }
}

// 获取可选的字典
function getSecletDictDetailById(row: any) {
  selectDetailList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { pid: row.dict } })
    .then((res: any) => {
      selectDetailList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取可选的字典失败',VxeNotifyType.error)
    });
}
// 自动生成
function getBdsResult(code: any, value: any, row: any) {
  const dict = dictList.find((it: any) => it.classify == '2');
  const expression = dict.expression;
  row[dict.code] = funBdsJsResult(expression, value);
  //dictList.find((it) => it.classify == '2').correField == item.code
}

//动态表输入

// 获取设计模式 选择字典
function findAllTableList() {
  tableList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictTable/findAllTableList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { grade: 0 } })
    .then((res: any) => {
      tableList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取获取设计模式选择字典失败',VxeNotifyType.error)
    });
}

function focusEvent() {
  tableData.length = 0;

  const $pulldown = proxy.$refs.pulldownRef;
  if ($pulldown) {
    tableData.push(...tableList);
    $pulldown.showPanel();
  }
}
function keyupEvent() {
  setTimeout(() => {
    tableData.length = 0;
    if (dictForm.correTable) {
      tableData.push(...tableList.filter((row) => (row.TABLE_NAME && row.TABLE_NAME.indexOf(dictForm.correTable) > -1) || (row.COMMENTS && row.COMMENTS.indexOf(dictForm.correTable) > -1)));
    } else {
      tableData.push(...tableList.slice(0));
    }
  }, 100);
}
function suffixClick() {
  const $pulldown = proxy.$refs.pulldownRef;
  if ($pulldown) {
    $pulldown.togglePanel();
  }
}
function cellClickEvent({ row }) {
  const $pulldown = proxy.$refs.pulldownRef;
  if ($pulldown) {
    dictForm.correTable = row.TABLE_NAME;
    getTableColumns();
    $pulldown.hidePanel();
  }
}

// 获取设计模式 选择字典
function getTableColumns() {
  correColumnList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictTable/getTableColumns';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { tableName: dictForm.correTable } })
    .then((res: any) => {
      correColumnList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取获取设计模式选择字典失败',VxeNotifyType.error)
    });
}

// 获取可选的字典
function getTableDataList(row: any) {
  const columNameList = [];
  columNameList.push(row.correColumn);
  columNameList.push(row.correColumn2);
  console.log(row);

  tableDataList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictTableField/getTableFieldAndDataList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { tableName: row.correTable, columNameList: columNameList.join(',') } })
    .then((res: any) => {
      tableDataList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取可选的字典失败',VxeNotifyType.error)
    });
}

function selectTableData($event, item, row) {
  const tableData = tableDataList.find((tData) => tData[item.correColumn] == $event.value);
  row[item.correField] = tableData[item.correColumn2];
}

// 上传成功
function onSuccess(e) {
  if (e && e.status && e.status.code && e.status.code === 400) {
    VxeMessage(e.status.msg.replace('IOException: ', ''), VxeNotifyType.error);
    return;
  } else {
    findDictDetailList();
  }
}
//上传失败
function onError(e) {
  console.log('失败', e);
}

// 上传图片 弹框
function upload() {
  paramData.dictId = sltDict.id;
  paramData.grade = 1;
}
</script>

<style lang="scss" scoped>
#dictChildManage {
  height: 100%;
  // 附加按钮间距
  .button-blue {
    margin: 5px 0 5px 5px;
  }
  // 设计模式表格 预览模式表格
  .designTable,
  .previewTable {
    height: calc(100% - 40px);
  }
}
</style>
